package com.liujun.microserver.auth2.jwt.authserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * doc:进行jwt相关试验的授权服务器
 * 
 * @author liujun
 * @date 2018/07/08
 */
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {

	@Autowired
	private AuthenticationManager authenticationManager;

	@Bean
	public JwtAccessTokenConverter acctokenConverter() {
		JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
		converter.setSigningKey("test-secret");

		return converter;
	}

	@Bean
	public JwtTokenStore jwtTokenStore() {
		return new JwtTokenStore(acctokenConverter());
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory()
				// 指定接入的用户名
				.withClient("clientapp")
				// 连接的密码
				.secret("112233")
				// 权限
				.scopes("read_userinfo")
				// 授权模式支持3种，密码，授权码，以及刷新授权
				.authorizedGrantTypes("password", "authorization_code", "refresh_token");
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		// 使用密码模式需要指定manager
		endpoints.authenticationManager(authenticationManager)
				// 需要指定jwt的相关信息
				.tokenStore(jwtTokenStore())
				// jwt签名的key的信息
				.accessTokenConverter(acctokenConverter());
	}

}
